package nl.ajonker.nols.android;

import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import nl.ajonker.nols.android.pl.RailAdapter;
import nl.ajonker.railroad.bl.NetworkSwitchService;
import nl.ajonker.railroad.dl.SwitchRail;
import nl.ajonker.railroad.dl.Track;
import nl.ajonker.railroad.sl.LogProcessor;
import nl.ajonker.railroad.sl.SwitchListener;
import nl.ajonker.railroad.sl.SwitchService;

import java.io.IOException;

public class SwitchActivity extends ListActivity {
    private final Track track;
    private final SwitchService switchService;

    public SwitchActivity() {
        track = new Track();
        switchService = new NetworkSwitchService();
        switchService.setLogProcessor(new LogProcessor() {
            @Override
            public void processLog(String log) {
                Log.e("SwitchService", log);
            }
        });
        track.addListener(new SwitchListener() {
            @Override
            public boolean onSwitch(SwitchRail rail) {
                try {
                    switchService.performSwitch(rail);
                } catch (IOException e) {
                    return false;
                }
                return true;
            }
        });
    }

    // http://www.vogella.com/articles/AndroidListView/article.html
    // http://www.ezzylearning.com/tutorial.aspx?tid=1763429
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        RailAdapter adapter = new RailAdapter(this,
                R.layout.listview_item_row, track.getRails());
        setListAdapter(adapter);

        final TextView statusTextView = (TextView) findViewById(R.id.statusText);
        switchService.setLogProcessor(new LogProcessor() {
            @Override
            public void processLog(String log) {
                statusTextView.setText(log);
                Log.e("SwitchActivity", log);
            }
        });

        TextView networkTextView = (TextView) findViewById(R.id.networkText);
        networkTextView.setText("Host: " + switchService.getHostname() + " Port: " + switchService.getPort());

        switchService.initialize(track.getRails());
    }

    @Override
    protected void onListItemClick(ListView l, View view, int position, long id) {
        RailAdapter.RailHolder railHolder = (RailAdapter.RailHolder) view.getTag();
        track.switchRailPosition(railHolder.getRail().getName());
    }
}
